package com.hzcx.app.simplechat.chat.util;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.icu.util.ULocale;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;

import androidx.core.app.NotificationCompat;

import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.util.EMLog;
import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.chat.bean.ChatNoticeBean;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.chat.db.ChatNoticeListDao;
import com.hzcx.app.simplechat.ui.main.MainActivity;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.sp.SPUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * 消息通知相关
 */
public class ChatNoticeUtil {

    private static final String TAG = ChatNoticeUtil.class.getSimpleName();
    protected static final long[] VIBRATION_PATTERN = new long[]{0, 180, 80, 120};

    public static ChatNoticeUtil chatNoticeUtil = null;
    protected long lastNotifyTime;
    protected AudioManager audioManager;
    protected Vibrator vibrator;
    protected Ringtone ringtone = null;

    private static Context context;

    private NotificationManager manager;

    private static List<ChatNoticeBean> noticeList;

    public static ChatNoticeUtil getInstance(Context cxt) {
        if (chatNoticeUtil == null) {
            chatNoticeUtil = new ChatNoticeUtil();
            noticeList = new ArrayList<>();
            context = cxt;
        }
        return chatNoticeUtil;
    }

    /**
     * 新消息通知声音跟震动
     *
     * @param message
     */
    public void vibrateAndPlayTone(EMMessage message) {


        boolean b  = false;
        try{
            // TODO: 2022/7/24 会异常，找不到admin字段，后期排查
            b = LitePal.select("userName=?", message.getFrom()).find(ChatNoticeListDao.class).size() > 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        if (b) {
            LogUtils.d("已开启该用户消息免打扰，不做通知");
            return;
        }

        sendNotice(message);

        if (System.currentTimeMillis() - lastNotifyTime < 1000) {
            // received new messages within 2 seconds, skip play ringtone
            return;
        }

        try {
            lastNotifyTime = System.currentTimeMillis();

            if (audioManager == null) {
                audioManager = (AudioManager) MyApplication.getContext().getSystemService(Context.AUDIO_SERVICE);
            }
            // check if in silent mode
            if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
                LogUtils.e(TAG, "in slient mode now");
                return;
            }

            boolean isShock = (boolean) SPUtils.get(MyApplication.getContext(), Common.SWITCH_SHOCK, true);
            if (isShock) {
                if (vibrator == null) {
                    vibrator = (Vibrator) MyApplication.getContext().getSystemService(Context.VIBRATOR_SERVICE);
                }
                vibrator.vibrate(VIBRATION_PATTERN, -1);
            }

            boolean isVoice = (boolean) SPUtils.get(MyApplication.getContext(), Common.SWITCH_VOICE, true);
            if (!isVoice) {
                return;
            }

            if (ringtone == null) {
                Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                ringtone = RingtoneManager.getRingtone(MyApplication.getContext(), notificationUri);
                if (ringtone == null) {
                    LogUtils.d(TAG, "cant find ringtone at:" + notificationUri.getPath());
                    return;
                }
            }

            if (!ringtone.isPlaying()) {
                String vendor = Build.MANUFACTURER;
                ringtone.play();
                // for samsung S3, we meet a bug that the phone will
                // continue ringtone without stop
                // so add below special handler to stop it after 3s if
                // needed
                if (vendor != null && vendor.toLowerCase().contains("samsung")) {
                    Thread ctlThread = new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(3000);
                                if (ringtone.isPlaying()) {
                                    ringtone.stop();
                                }
                            } catch (Exception e) {
                            }
                        }
                    };
                    ctlThread.run();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 8.0以上创建渠道
     */
    public void createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "chat";
            String channelName = "聊天消息";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            createNotificationChannel(channelId, channelName, importance);
        }
    }

    /**
     * 发送通知栏消息
     *
     * @param message
     */
    private void sendNotice(EMMessage message) {

        try {

            if(!AppHelper.isBackground(context)){
                return;
            }

            String title = message.getStringAttribute(ChatConstant.EXTRA_SEND_USER_NICKNAME);
            String content = "";
            int id = message.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
            if (message.getType() == EMMessage.Type.TXT) {
                EMTextMessageBody body = (EMTextMessageBody) message.getBody();
                content = body.getMessage();
            } else if (message.getType() == EMMessage.Type.IMAGE) {
                content = "图片";
            } else if (message.getType() == EMMessage.Type.LOCATION) {
                content = "位置";
            } else if (message.getType() == EMMessage.Type.VOICE) {
                content = "语音消息";
            } else if (message.getType() == EMMessage.Type.CUSTOM) {
                EMCustomMessageBody body = (EMCustomMessageBody) message.getBody();
                if (ChatConstant.EXTRA_CUSTOM_SHARE.equals(body.event())) {
                    content = "个人名片";
                } else if (ChatConstant.EXTRA_CUSTOM_RECALL.equals(body.event())) {
                    content = "撤回了一条消息";
                } else {
                    content = "未知消息";
                }
            } else {
                content = "未知消息";
            }

            boolean isHave = false;
            for (int i = 0; i < noticeList.size(); i++) {
                if (noticeList.get(i).getId() == id) {
                    noticeList.get(i).setNum(noticeList.get(i).getNum() + 1);
                    content = "[" + noticeList.get(i).getNum() + "条]:" + content;
                    isHave = true;
                }
            }
            if (!isHave) {
                ChatNoticeBean bean = new ChatNoticeBean(id, 1);
                noticeList.add(bean);
            }

            manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            Notification notification = new NotificationCompat.Builder(context, "chat")
                    .setContentTitle(title)
                    .setContentText(content)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                    .setAutoCancel(true)
                    .setContentIntent(getNoticeIntent())
                    .build();
            manager.notify(id, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PendingIntent getNoticeIntent() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(MainActivity.INTENT_NOTICE, true);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 1001, intent, PendingIntent.FLAG_ONE_SHOT);
        return pendingIntent;
    }

    /**
     * 清除通知栏消息
     *
     * @param message
     */
    public void clearNotice(EMMessage message) {
        try {
            int id;
            if (message.direct() == EMMessage.Direct.SEND) {
                id = message.getIntAttribute(ChatConstant.EXTRA_RECEIVE_USER_ID);
            } else {
                id = message.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
            }
            Iterator<ChatNoticeBean> iterator = noticeList.iterator();
            while (iterator.hasNext()){
                if (iterator.next().getId()==id){
                    iterator.remove();
                }
            }
            if (manager!= null){
                manager.cancel(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

}
